package com.cxt.service.impl;

//import com.baomidou.entity.TripInfo;
//import com.baomidou.mapper.TripInfoMapper;TripInfoMapper
//import com.baomidou.service.ITripInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cxt.Mapper.TripInfoMapper;
import com.cxt.context.BaseContext;
import com.cxt.dto.WayVo;
import com.cxt.entity.*;
import com.cxt.exception.BaseException;
import com.cxt.service.*;
import com.cxt.utils.DistanceUtil;
import com.cxt.vo.TripInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 行程信息表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-02-27
 */
@Service
public class TripInfoServiceImpl extends ServiceImpl<TripInfoMapper, TripInfo> implements ITripInfoService {

    @Autowired
    private IWaypointInfoService waypointInfoService;
    @Autowired
    private ICarpoolInfoService carpoolInfoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private ITripOrderService  tripOrderService;
    @Autowired
    private IMessageNotificationService  messageNotificationService;
    @Override
    public List<TripInfoVo> getTripInfo() {
        //组件行程信息
        List<TripInfoVo> tripInfoVoList = new ArrayList<>();
        Long id = BaseContext.getCurrentId();
        //查询自己属于团长的行程
        List<TripInfo> tripInfoList = this.list(
                new LambdaQueryWrapper<TripInfo>()
                        .eq(TripInfo::getGroupLeaderId, id)
                        .eq(TripInfo::getTripStatus,1)
                        .or()
                        .eq(TripInfo::getGroupLeaderId, id)
                        .eq(TripInfo::getTripStatus,2));
        //查询途径点
        for (TripInfo tripInfo : tripInfoList) {
            Long carpoolInfoId = tripInfo.getCarpoolInfoId();
            //根据拼车id查询途径点，按照type生序
            LambdaQueryWrapper<WaypointInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WaypointInfo::getCarpoolInfoId, carpoolInfoId)
                    .orderByAsc(WaypointInfo::getWaypointType);
            List<WaypointInfo> waypointInfoList = waypointInfoService.list(queryWrapper);
            tripInfoVoList.add(
                    TripInfoVo.builder()
                            .tripInfo(tripInfo)
                            .waypointInfoList(waypointInfoList)
                            .tripUserRelation(1)
                            .build());
        }
        //查询自己属于司机的行程
        List<TripInfo> tripInfoList1 = this.list(
                new LambdaQueryWrapper<TripInfo>()
                        .eq(TripInfo::getDriverId, id)
                        .eq(TripInfo::getTripStatus,1)
                        .or()
                        .eq(TripInfo::getDriverId, id)
                        .eq(TripInfo::getTripStatus,2));
        for (TripInfo tripInfo : tripInfoList1) {
            Long carpoolInfoId = tripInfo.getCarpoolInfoId();
            LambdaQueryWrapper<WaypointInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WaypointInfo::getCarpoolInfoId, carpoolInfoId)
                    .orderByAsc(WaypointInfo::getWaypointType);
            List<WaypointInfo> waypointInfoList = waypointInfoService.list(queryWrapper);
            tripInfoVoList.add(
                    TripInfoVo.builder()
                            .tripInfo(tripInfo)
                            .waypointInfoList(waypointInfoList)
                            .tripUserRelation(2)
                            .build()
            );
        }
        //查询自己属于乘客的行程
        List<TripInfo> tripInfoList2 = this.list(
                new LambdaQueryWrapper<TripInfo>().like(TripInfo::getMemberIds,id.toString())
                        .eq(TripInfo::getTripStatus,1)
                        .or()
                        .like(TripInfo::getMemberIds,id.toString())
                        .eq(TripInfo::getTripStatus,2));
        for (TripInfo tripInfo : tripInfoList2) {
            Long carpoolInfoId = tripInfo.getCarpoolInfoId();
            LambdaQueryWrapper<WaypointInfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(WaypointInfo::getCarpoolInfoId, carpoolInfoId)
                    .orderByAsc(WaypointInfo::getWaypointType);
                    List<WaypointInfo> waypointInfoList = waypointInfoService.list(queryWrapper);
            tripInfoVoList.add(
                    TripInfoVo.builder()
                            .tripInfo(tripInfo)
                            .waypointInfoList(waypointInfoList)
                            .tripUserRelation(3)
                    .build()
            );
        }
        return tripInfoVoList;
    }
    @Override
    @Transactional
    public List<TripInfoVo> getTripInfoEnd() {
        //组件行程信息
        List<TripInfoVo> tripInfoVoList = new ArrayList<>();
        Long id = BaseContext.getCurrentId();
        //查询自己属于团长的行程
        List<TripInfo> tripInfoList = this.list(
                new LambdaQueryWrapper<TripInfo>().eq(TripInfo::getGroupLeaderId, id)
                        .eq(TripInfo::getTripStatus,3));
        //查询途径点
        for (TripInfo tripInfo : tripInfoList) {
            Long carpoolInfoId = tripInfo.getCarpoolInfoId();
            List<WaypointInfo> waypointInfoList = waypointInfoService.getWaypointInfoByCarpoolId(carpoolInfoId);
            tripInfoVoList.add(
                    TripInfoVo.builder()
                            .tripInfo(tripInfo)
                            .waypointInfoList(waypointInfoList)
                            .tripUserRelation(1)
                            .build());
        }
        //查询自己属于司机的行程
        List<TripInfo> tripInfoList1 = this.list(
                new LambdaQueryWrapper<TripInfo>().eq(TripInfo::getDriverId, id)
                        .eq(TripInfo::getTripStatus,3));
        for (TripInfo tripInfo : tripInfoList1) {
            Long carpoolInfoId = tripInfo.getCarpoolInfoId();
            List<WaypointInfo> waypointInfoList = waypointInfoService.getWaypointInfoByCarpoolId(carpoolInfoId);
            tripInfoVoList.add(
                    TripInfoVo.builder()
                            .tripInfo(tripInfo)
                            .waypointInfoList(waypointInfoList)
                            .tripUserRelation(2)
                            .build()
            );
        }
        //查询自己属于乘客的行程
        List<TripInfo> tripInfoList2 = this.list(
                new LambdaQueryWrapper<TripInfo>().like(TripInfo::getMemberIds,id.toString())
                        .eq(TripInfo::getTripStatus,3));
        for (TripInfo tripInfo : tripInfoList2) {
            Long carpoolInfoId = tripInfo.getCarpoolInfoId();
            List<WaypointInfo> waypointInfoList = waypointInfoService.getWaypointInfoByCarpoolId(carpoolInfoId);
            tripInfoVoList.add(
                    TripInfoVo.builder()
                            .tripInfo(tripInfo)
                            .waypointInfoList(waypointInfoList)
                            .tripUserRelation(3)
                            .build()
            );
        }
        return tripInfoVoList;
    }

    @Override
    public boolean quit(Long id) {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<TripInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TripInfo::getId, id);
        TripInfo one = this.getOne(queryWrapper);
        //获取ids的list
        String memberIds = one.getMemberIds();
        List<Long> memberIdList = new ArrayList<>();
        if (memberIds != null && !memberIds.trim().isEmpty()) {
            memberIdList = Arrays.stream(memberIds.split(","))
                    .map(String::trim)
                    .filter(s -> !s.isEmpty())
                    .map(Long::valueOf)
                    .collect(Collectors.toList());
        }
        //如果成员在list存在
        if (memberIdList.contains(userId)) {
            //删除行程信息
            boolean remove = this.removeById(id);
            //修改拼车信息
            if (remove) {
                //拼车信息
                CarpoolInfo carpoolInfo = carpoolInfoService.getById(one.getCarpoolInfoId());
                //拼车人数
                Integer carpoolNum = carpoolInfo.getPassengerCount();
                //拼车人数-1
                carpoolNum--;
                //拼车信息修改
                carpoolInfo.setPassengerCount(carpoolNum);
                //拼车状态，改成1
                carpoolInfo.setCarpoolStatus(1);
                //移除成员id
                memberIdList.remove(userId);
                StringBuilder sb = new StringBuilder();
                for (Long l : memberIdList) {
                    //给成员发送行程取消信息
                    messageNotificationService.addMassage(l,"有成员退出行程，行程已取消，请注意查看拼车信息");
                }
                //给团长发
                messageNotificationService.addMassage(carpoolInfo.getGroupLeaderId(),"有成员退出行程，行程已取消，请注意查看拼车信息");
                //给司机发
                messageNotificationService.addMassage(carpoolInfo.getDriverId(),"司机您好，拼车已取消，请合理安排接驾时间");
                for (Long memberId : memberIdList) {
                    sb.append(memberId).append(",");
                }
                carpoolInfo.setMemberIds(sb.toString());
                //删除该用户的途径点
                LambdaQueryWrapper<WaypointInfo> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(WaypointInfo::getUserId, userId)
                        .eq(WaypointInfo::getCarpoolInfoId, one.getCarpoolInfoId());
                waypointInfoService.remove(queryWrapper1);
                carpoolInfoService.updateById(carpoolInfo);
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean start(Long id) {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<TripInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TripInfo::getId, id);
        TripInfo one = this.getOne(queryWrapper);
        if (one.getDriverId().equals(userId)) {
            one.setTripStatus(2);
            updateById(one);
            //给所有成员发送信息
            LambdaQueryWrapper<WaypointInfo> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(WaypointInfo::getCarpoolInfoId, one.getCarpoolInfoId());
            List<WaypointInfo> list = waypointInfoService.list(queryWrapper1);
            for (WaypointInfo waypointInfo : list) {
                if(waypointInfo.getWaypointType()==1){
                    continue;
                }
                messageNotificationService.addMassage(waypointInfo.getUserId(),"行程已开始，请保持接驾");
            }
            return true;
        }
        return false;
    }
    @Override
    @Transactional
    public Boolean waypointStatus(WayVo wayVo) {
        //找到该途径点
        WaypointInfo waypointInfo = waypointInfoService.getById(wayVo.getWaypointId());
        double v = DistanceUtil.calculateDistanceByLonLat(waypointInfo.getLatitude().doubleValue(), waypointInfo.getLongitude().doubleValue(),
                wayVo.getLat().doubleValue(), wayVo.getLng().doubleValue());
        if(v/1000>1){
            throw new BaseException("距离太远");
        }
        if(waypointInfo.getWaypointType()==3){
            //判断手机号
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getId,waypointInfo.getUserId());
            User one = userService.getOne(queryWrapper);
            //获取手机号的后四位
            String phone = one.getPhone().substring(one.getPhone().length() - 4);
            if(!phone.equals(wayVo.getGroupLeaderPhone())){
                throw new BaseException("手机号尾号错误");
            }
        }
        //修改途径点状态
        waypointInfo.setStatus(2);
        //修改已送到ids
        LambdaQueryWrapper<TripInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TripInfo::getId, wayVo.getTripId());
        //保存途径点信息
        waypointInfoService.updateById(waypointInfo);
        TripInfo one = this.getOne(queryWrapper);
//        one.setPassedWaypoints((one.getPassedWaypoints()!=null?one.getPassedWaypoints()+",":"")+waypointInfo.getId().toString());
        //判断行程是否结束
        //获取所有途径点，且所有途径点都是已到就是行程结束
        //设置已行驶距离
        Integer status = 2;
        one.setTraveledDistance(wayVo.getCurrentDistance());
        List<WaypointInfo> waypointInfoList = waypointInfoService.getWaypointInfoByCarpoolId(one.getCarpoolInfoId());
        for (WaypointInfo waypointInfo1 : waypointInfoList) {
            if(waypointInfo1.getStatus()!=2&&waypointInfo.getWaypointType()!=1){
                status  = 2;
                break;
            }
            if(waypointInfo1.getStatus()==2&&waypointInfo.getWaypointType()==1){
                status  = 3;
                tripOrderService.add(one);
                break;
            }
        }
        if(status==3){
            //行程结束
            //给所有成员发送信息
            LambdaQueryWrapper<WaypointInfo> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(WaypointInfo::getCarpoolInfoId, one.getCarpoolInfoId());
            List<WaypointInfo> list = waypointInfoService.list(queryWrapper1);
            for (WaypointInfo waypointInfo1 : list) {
                if(waypointInfo1.getWaypointType()==1){
                    continue;
                }
                messageNotificationService.addMassage(waypointInfo1.getUserId(),"行程已结束，请注意订单信息及时支付");
            }
        }
        one.setTripStatus(status);
        updateById(one);
        return true;
    }
}
